package com.ssm.controller;

import com.ssm.domain.SysLog;
import com.ssm.service.SysLogService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextListener;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

@Component
@Aspect
public class LogAop {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysLogService sysLogService;

    private Date visitTime;//开始时间
    private Class<?> clazz;
    private Method method;

    @Before("execution(* com.ssm.controller.*.*(..))")
    public void doBefore(JoinPoint joinPoint) throws NoSuchMethodException {
        //获取开始访问时间
        visitTime = new Date();
        //具体访问类
        clazz = joinPoint.getTarget().getClass();
        //访问方法名
        String methodStr = joinPoint.getSignature().getName();
        //获取参数
        Object[] args = joinPoint.getArgs();

        //获取方法
        //无参数
        if (args == null || args.length == 0) {
            method = clazz.getMethod(methodStr);
        } else {
            //有参数
            Class<?>[] paramTypes = new Class<?>[args.length];
            for (int i = 0; i < args.length; i++) {
                paramTypes[i] = args[i].getClass();
            }
            method = clazz.getMethod(methodStr, paramTypes);
        }
    }

    @After("execution(* com.ssm.controller.*.*(..))")
    public void doAfter(JoinPoint joinPoint) {
        //访问时长
        long time = new Date().getTime() - visitTime.getTime(); //获取访问的时长
        //获取url
        StringBuilder _url = new StringBuilder();
        if (clazz != null && method != null && clazz != LogAop.class) {
            //获取类上路径 @RequestMapping("/user")
            RequestMapping clazzAnnotation = clazz.getAnnotation(RequestMapping.class);
            if (clazzAnnotation != null) {
                String[] value = clazzAnnotation.value();
                _url.append(value[0]);
            }
            //获取方法路径 建议控制使用统一注解@RequestMapping,方便这里获取
            RequestMapping methodAnnotation = method.getAnnotation(RequestMapping.class);
            if (methodAnnotation != null) {
                String[] value = methodAnnotation.value();
                _url.append(value[0]);
            } else {
                GetMapping getMapping = method.getAnnotation(GetMapping.class);
                if (getMapping != null) {
                    String[] value = getMapping.value();
                    _url.append(value[0]);
                } else {
                    PostMapping postMapping = method.getAnnotation(PostMapping.class);
                    if (postMapping != null) {
                        String[] value = postMapping.value();
                        _url.append(value[0]);
                    }
                }

            }


            //获取ip
            String ip = request.getRemoteAddr();

            //获取当前用户名
            SecurityContext context = SecurityContextHolder.getContext();
            //这里是 org.springframework.security.core.userdetails.User;
            User principal = (User) context.getAuthentication().getPrincipal();
            String username = principal.getUsername();

            //将日志相关信息封装到SysLog对象
            SysLog sysLog = new SysLog();
            sysLog.setExecutionTime(time); //执行时长
            sysLog.setIp(ip);
            sysLog.setMethod("[类名] " + clazz.getName() + "[方法名] " + method.getName());
            sysLog.setUrl(_url.toString());
            sysLog.setUsername(username);
            sysLog.setVisitTime(visitTime);

            //调用Service完成操作
            sysLogService.save(sysLog);
        }

    }


}
